/**
 * copyright (c) 2017-2023 厦门风领科技有限公司
 * https://www.fengling.cn/
 * 
 * HTTP同步网络请求
 * zengbinsi
 * 2020-08-14 16:31:12
 */




 
export class GGNetHTTPAsync {

    /**
     * 基于Promise的同步GET请求
     * @param router 路由
     * @param headParams 请求头参数
     */
    static get(router: string, headParams?: any): Promise<any> {
        return new Promise((resolve, reject) => {
            GGNetHTTPAsync.sendRequerst('GET', router, {}, headParams, (err, res) => {
                if (err) {
                    return reject(err);
                }

                return resolve(res);
            });
        });
    }

    /**
     * 基于Promise的同步POST请求
     * @param router 路由
     * @param params 请求体参数
     * @param headParams 请求头参数
     */
    static post(router: string, params: any, headParams?: any): Promise<any> {
        return new Promise((resolve, reject) => {
            GGNetHTTPAsync.sendRequerst('POST', router, params, headParams, (err, res) => {
                if (err) {
                    return reject(err);
                }

                return resolve(res);
            });
        });
    }

    /**
     * 基于Promise的同步PUT请求
     * @param router 路由
     * @param params 请求体参数
     * @param headParams 请求头参数
     */
    static put(router: string, params: any, headParams?: any): Promise<any> {
        return new Promise((resolve, reject) => {
            GGNetHTTPAsync.sendRequerst('PUT', router, params, headParams, (err, res) => {
                if (err) {
                    return reject(err);
                }

                return resolve(res);
            });
        });
    }

    /**
     * 基于Promise的同步DELETE请求
     * @param router 路由
     * @param params 请求体参数
     * @param headParams 请求头参数
     */
    static delete(router: string, params: any, headParams?: any): Promise<any> {
        return new Promise((resolve, reject) => {
            GGNetHTTPAsync.sendRequerst('DELETE', router, params, headParams, (err, res) => {
                if (err) {
                    return reject(err);
                }

                return resolve(res);
            });
        });
    }

    /**
     * 发送请求
     * @param type 请求类型
     * @param router 路由
     * @param params 请求体参数
     * @param headParams 请求头参数
     * @param callback 回调
     */
    static sendRequerst(type: string, router: string, params: any, headParams: any, callback: Function) {
        let xhr = new XMLHttpRequest();
        //readyState属性改变时会调用
        xhr.onreadystatechange = () => {
            if (xhr.readyState !== EHttpReadyState.DONE) {
                return;
            }
            let res;

            if (xhr.status >= 200 && xhr.status < 400) {
                try {
                    res = gg.parseJSON(xhr.responseText);
                } catch (error) {
                    return callback(error, undefined);
                }
                callback(undefined, res || xhr.responseText);
            } else {
                try {
                    res = gg.parseJSON(xhr.responseText);
                } catch (error) {
                    res = xhr.responseText;
                }
                callback(res || xhr, undefined);
                xhr.status > 499 && GGNetHTTPAsync.sendWarning(router, xhr.responseText);
            }
        }

        xhr.open(type, router, true);
        //设置提交数据的方式，application/json json传输数据用的比较多
        xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
        xhr.setRequestHeader("client-os", cc.sys.os);
        (window as any).userData && xhr.setRequestHeader("x-access-token", (window as any).userData.token || '');
        xhr.setRequestHeader("client-ver", (window as any).APP_VERSION);
        xhr.setRequestHeader("appid", (window as any).APP_ID);     
        
        // 字节投放微信小游戏
        if (true) {
            xhr.setRequestHeader('clue_token', window['clue_token']);
            xhr.setRequestHeader('ad_id', window['ad_id']);
            xhr.setRequestHeader('creative_id', window['creative_id']);
        }

        if (headParams) {
            for (var key in headParams) {
                if (key === "Content-Type" || key === "client-os" || key === "client-ver" || key === "x-access-token") {
                } else {
                    xhr.setRequestHeader(key, headParams[key]);
                }
            }
        }

        try {
            if (type === 'GET') {
                xhr.send();
            } else {
                xhr.send(gg.stringifyJSON(params));
            }
        } catch (error) {
            cc.error(error);
        }
    }

    /** 接口警报 */
    static sendWarning(url, msg) {
        const GGStore = (window as any).GGStore;
        if (GGStore) {
            const gameBad = GGStore.getTodayValue(`${(window as any).APP_ID}_gameBad`, 0);
            if (gameBad) { return; }

            GGStore.setTodayValue(`${(window as any).APP_ID}_gameBad`, 1);
        }
        try {
            GGNetHTTPAsync.post('https://warning.feigo.fun/api/warning/game-bad', {
                name: (window as any).GAME_NAME,
                appid: (window as any).APP_ID,
                url,
                msg
            });
        } catch (error) { }
    }
}

(window as any).GGNetHTTPAsync = GGNetHTTPAsync;


/**读取状态 */
export enum EHttpReadyState {
    /**未打开 open()方法还未调用 */
    UNSENT = 0,
    /**未发送 open()方法被调用 */
    OPENED = 1,
    /**已获取响应头 send()方法已经被调用, 响应头和响应状态已经返回. */
    HEADERS_RECEIVED = 2,
    /**正在下载响应体 响应体下载中,responseText中已经获取了部分数据.*/
    LOADING = 3,
    /**请求完成  整个请求过程已经完毕*/
    DONE = 4
}
